<template>
  <a-modal
    v-model:visible="show"
    title="绑定点位"
    width="1200px"
    height="800px"
    class="dispatchContainer"
    :confirm-loading="confirmLoading"
    @ok="ok"
  >
    <div>
      <SearchForm
        :keyword-search-data="[{ key: 'searchText', label: '点位名称' }]"
        :show-add-btn="false"
        @search="handleSearch"
      />
      <SlTable
        :columns="columns"
        row-key="userId"
        :data-source="tableData"
        :loading="tableLoading"
        :pagination="pagination"
        :scroll="{ x: 'auto', y: '400px' }"
      >
        <template #bodyCell="{ column, record }">
          <StateTag
            v-if="column.dataIndex === 'bandStatus'"
            :color="record.bandStatus ? '#38CE7B' : '#F56D6A'"
            :value="record.bandStatus ? '已绑定' : '待绑定'"
            class="h-6 ml-2 px-2"
          ></StateTag>
          <a-space v-if="column.dataIndex === 'oper'">
            <PermissionBtn
              :btn-props="{ type: 'link' }"
              :oper-type="OperPermissionType.MANAGE"
              @click="bandSet(record)"
            >
              绑定点位
            </PermissionBtn>
          </a-space>
        </template>
      </SlTable>
    </div>
  </a-modal>
</template>
<script lang="ts" setup>
import { useI18n } from "/@/locales/useI18n";
import { ref, watch, nextTick, createVNode } from "vue";
import { FormItemData, FormItemComponentType, DynamicFormExpose } from "/@/components/CURDDialog/models";
import { CancelApplyItem } from "/@/api/aiot/serviceApply/models";
import { OperPermissionType } from "/@/api/aiot/role/models";
import { Api } from "/@/api/aiot/gateway";
import { bandEquipmentAttributes } from "/@/api/aiot/equipmentType";
import { useCURD } from "/@/hooks/useCURD";
import { message, Modal, TableColumnProps } from "ant-design-vue";
import { GatewayItem, GatewayPointItem, GatewayTypeAttrItem } from "/@/api/aiot/gateway/models";
import { TableRecord } from "/@/api/models";
import { colors } from "/@/style/style";
import { GatewayModalPropsOptions } from "/@/api/aiot/equipment/models";

const { t } = useI18n();
const confirmLoading = ref<boolean>(false);
const show = ref<boolean>(false);
const { tableData, tableLoading, curd, reloadTable, pagination, searchModel } = useCURD<GatewayPointItem>({
  getPageUrl: Api.gatewayDataPointsPage,
  loadOnMounted: false,
  loadFilter(data) {
    data.forEach((el) => {
      let datapointAttrs: any;
      try {
        datapointAttrs = JSON.parse(el.datapointAttrs);
      } catch (err) {}
      if (datapointAttrs) {
        const pointObj: any = {};
        for (let key in datapointAttrs) {
          const target = columns.value.find((el) => el.title === key);
          if (target) {
            pointObj[target.dataIndex as string] = datapointAttrs[key];
          }
        }
        Object.assign(el, pointObj);
      }
    });
    return data;
  },
});
const props = defineProps<{
  options?: GatewayModalPropsOptions;
  visible: boolean;
}>();
const model = ref<CancelApplyItem>({
  cancelReasonType: "",
  serviceOrderCancelType: "",
  cancelReason: "",
});
const columns = ref<TableColumnProps<any>[]>([]);

const isEmpty = ref(false);
const visible = ref(false);
const {
  tableData: attrData,
  tableLoading: attrLoading,
  reloadTable: reloadAttr,
} = useCURD<GatewayTypeAttrItem>({
  getPageUrl: Api.getGatewayTypeAttrs,
  loadOnMounted: false,
  pageSize: 999,
  loadFilter(data) {
    data.sort((a, b) => {
      return a.datapointAttrNumber - b.datapointAttrNumber;
    });
    return data;
  },
});
//第一次打开
const dyForm = ref<DynamicFormExpose>();
const emits = defineEmits(["ok", "update:visible"]);
let firstShow = true;
watch(show, (v) => {
  emits("update:visible", v);
  if (firstShow) {
    firstShow = false;
  }
  if (v) {
    // reloadTable({ model: { gatewayId: props.options?.gatewayId } });
  }
});
watch(
  () => props.visible,
  async (v) => {
    show.value = v;
    if (!v) {
      reset();
    } else {
      await reloadAttr({ model: { gatewayTypeId: props.options?.gatewayTypeId } });
      isEmpty.value = attrData.value.length === 0;
      if (!isEmpty.value) {
        const newColumns: TableColumnProps<any>[] = attrData.value.map((el) => ({
          title: el.datapointAttrName,
          dataIndex: `attr${el.datapointAttrNumber}`,
          width: "120px",
        }));
        const newModel: any = {};
        attrData.value.forEach((attr, i) => {
          newModel[`attr${i}`] = "";
        });
        model.value = newModel;
        newColumns[0].fixed = "left";
        newColumns.push({
          title: "绑定状态",
          dataIndex: "bandStatus",
          width: "120px",
        });
        newColumns.push({
          title: "操作",
          dataIndex: "oper",
          fixed: "right",
        });
        columns.value = newColumns;
        nextTick(() => {
          dyForm.value?.initFormItemComponentData();
        });
        reloadTable({ model: { gatewayId: props.options?.gatewayId } });
      }
    }
  }
);

watch(
  () => props.options,
  (v) => {},
  { deep: true }
);
function reset() {
  if (dyForm.value) {
    dyForm.value.resetFields();
  }
}
async function bandSet(row) {
  var req;
  if (row.bandStatus) {
    Modal.confirm({
      title: "您确定绑定点位吗？",
      content: createVNode("div", { style: `color: ${colors.secondary};` }, "绑定后，将有多个设备属性绑定该点位"),
      async onOk() {
        req = await bandEquipmentAttributes({
          equipmentAttributeId: props.options?.equipmentAttributeId || "",
          gatewayDatapointId: row.gatewayDatapointId,
        });
        if (req) {
          message.success("操作成功");
          emits("ok");
          show.value = false;
          reloadTable({ model: { gatewayId: props.options?.gatewayId } });
        }
      },
    });
  } else {
    req = await bandEquipmentAttributes({
      equipmentAttributeId: props.options?.equipmentAttributeId || "",
      gatewayDatapointId: row.gatewayDatapointId,
    });
    if (req) {
      message.success("操作成功");
      emits("ok");
      show.value = false;
      reloadTable({ model: { gatewayId: props.options?.gatewayId } });
    }
  }
}
function ok() {
  if (!dyForm.value) return;
  dyForm.value
    .validate()
    .then(async (data: CancelApplyItem) => {})
    .catch(() => {});
}
async function handleSearch({ searchText }) {
  reloadTable({ model: { searchText } });
}
</script>
<style scoped lang="less">
:deep(.ant-tabs-tab-btn) {
  font-size: 16px;
}
:deep(.ant-table-container) {
  height: 450px;
}
</style>
